<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/4/18
 * Time: 下午4:39
 */

namespace backend\controllers;

use backend\models\UserCouponSearch;
use common\models\UserCoupon;
use yii\web\Controller;
use yii;
use yii\web\NotFoundHttpException;

class UserCouponController extends Controller
{
    public function actionIndex()
    {


        $searchModel = new UserCouponSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->get());
        return $this->render('index', ['model' => $searchModel, 'dataProvider' => $dataProvider]);
    }
    public function actionSync(){

        $user_coupon_collection = UserCoupon::getCollection()->find();
        foreach($user_coupon_collection as $item){
            $model = UserCoupon::findOne(['user_id'=>$item['user_id'],'coupon_id'=>$item['coupon_id']]);
            if(empty($model)){
                $model=new UserCoupon();
                $model->setAttributes($item);
                $model->save();
            }else{
                $model->setAttributes($item);
                $model->save();
            }


        };
        return $this->redirect(['index']);
    }
    public function actionDelete($id){
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }
    protected function findModel($id)
    {
        if (($model = UserCoupon::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
